import { Bar } from '@ant-design/plots';
import React from 'react';
import { countUserbyDept } from '../../services/userServices';

class BarChart extends React.PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      config: {
        data: [],
        xField: 'deptName',
        yField: 'userCount',
        paddingRight: 80,
        style: {
          maxWidth: 25,
        },
        markBackground: {
          label: {
            text: ({ originData }) => {
              const { data } = this.state.config;
              const totalUserCount = data.reduce((sum, item) => sum + item.userCount, 0);
              return `${((originData.userCount / totalUserCount) * 100).toFixed(2)}% | ${originData.userCount}`;
            },
            position: 'right',
            dx: 80,
            style: {
              fill: '#aaa',
              fillOpacity: 1,
              fontSize: 14,
            },
          },
          style: {
            fill: '#eee',
          },
        },
        scale: {
          y: {
            domain: [0, 10],
          },
        },
        axis: {
          x: {
            tick: false,
            title: false,
          },
          y: {
            grid: false,
            tick: false,
            label: false,
            title: false,
          },
        },
        interaction: {
          elementHighlight: false,
        },
      },
    };
    this.initData();
  }

  initData = async () => {
    try {
      const response = await countUserbyDept();
      const { data } = response;
      this.setState({
        config: {
          ...this.state.config,
          data: data,
        },
      });
    } catch (error) {
      console.log(error.message || 'Failed to count user');
    }
  }

  render() {
    return (
      <Bar {...this.state.config} />
    );
  }
}

export default BarChart;
